#!/usr/bin/python
# -*- coding: iso-8859-15 -*-

import re
import os 
import urllib2
import sys

BASE_URL = 'http://www.guiadosquadrinhos.com/'
BASE_THUMB_IMG_URL = BASE_URL + 'images/thumb/'
DATA_FOLDER = '../assets/data/'

class Issue:
  number = None
  title = None
  year = None
  month = None
  pictureName = None
  pictureUrl = None
  url = None
  license = None
  category = None
  status = None
  pages = None
  pageFormat = None
  publisher = None

  urls = None
  serieTitle = None

  def __init__(self, url):
    self.url = BASE_URL + url.replace('&amp;', '&')

    print 'Downloading issue at %s ...' % (self.url)

    fileHandle = urllib2.urlopen(self.url)
    self.page = fileHandle.read()
    fileHandle.close()

  def downloadPicture(self, serieId):
    print '  ... downloading picture %s' % self.pictureUrl

    if (self.pictureUrl == None):
      self.pictureUrl = ""
      return self

    try:
      filePicture = urllib2.urlopen(self.pictureUrl)

      fout = open(serieId + '/' + self.pictureName, "wb")
      fout.write(filePicture.read())
      fout.close()

      filePicture.close()

    except urllib2.HTTPError, e:
      if e.code == 404:
        print "\n    --> Problem fetching the picture %s \n" % (self.pictureUrl) 
        self.pictureUrl = ""
        self.pictureName = ""
      else:
        raise

    return self

  def parse(self):
    print '  ... parsing'

    match = re.search(r'<img src="ShowImage.*?path=(.*?.jpg)', self.page, re.DOTALL) 
    if match:
      self.pictureUrl = BASE_THUMB_IMG_URL + match.group(1).replace('.jpg', 't.jpg').replace('xt.jpg','t.jpg')
      self.pictureName = self.pictureUrl.rsplit('/').pop()
    
    self.serieTitle = None
    match = re.search(r'<div class="centro"><br/>\s*<h1>(.*?)\s*n&deg;&nbsp;(\d+)\s*</h1>', self.page, re.DOTALL) 
    if match:
      self.serieTitle = match.group(1)
      self.number = match.group(2)
    else:
      match = re.search(r'<div class="centro"><br/>\s*<h1>(.*?)\s*</h1>', self.page, re.DOTALL) 
      if match:
        self.serieTitle = match.group(1)
        self.number = "-"

    self.serieTitle = re.sub('\s+', ' ', self.serieTitle)
    self.serieTitle = re.sub(' \& ', ' and ', self.serieTitle)

    match = re.search(r'<strong>Licenciador:\s*</strong>\s*(.*?)\s*<br', self.page, re.DOTALL) 
    if match:
      self.license = re.sub('\s+', ' ', match.group(1))

    match = re.search(r'<strong>Publicado em:\s*</strong>\s*(.*?)\s*de\s*(\d+)\s*<br', self.page, re.DOTALL) 
    if match:
      self.month = re.sub('\s+', ' ', match.group(1))
      self.year = re.sub('\s+', ' ', match.group(2))
    else:
      match = re.search(r'<strong>Publicado em:\s*</strong>\s*(\d+)\s*', self.page, re.DOTALL) 
      if match:
        self.year = re.sub('\s+', ' ', match.group(1))
        self.month = ""

    match = re.search(r'<strong>Editora:</strong>\s*<a href=.*?>\s*(.*?)\s*</a>', self.page, re.DOTALL) 
    if match:
      self.publisher = match.group(1)

    match = re.search(r'<strong>Categoria:</strong>\s*(.*?)\s*<br/?>', self.page, re.DOTALL) 
    if match:
      self.category = match.group(1)

    match = re.search(r'<strong>Status:</strong>\s*(.*?)\s*<br/?>', self.page, re.DOTALL) 
    if match:
      self.status = match.group(1)

    match = re.search(r'<strong>N&uacute;mero de p&aacute;ginas:</strong>\s*(.*?)\s*<br/?>', self.page, re.DOTALL) 
    if match:
      self.pages = match.group(1)

    match = re.search(r'<div class="boxedicao1">\s*(.*?)\s*<br/>\s*<strong>Publicado', self.page, re.DOTALL) 
    if match:
      self.title = re.sub('\&', ' ', match.group(1))

    self.urls = re.findall(r'<a href="(edicao\.aspx.*?)">\d+</a>', self.page, re.DOTALL)

    return self

  def __str__(self):
    title = ""
    if self.title:
      title = "\n      <subtitle>%s</subtitle>" % (self.title)

    return '''    <issue number="%s">%s
      <url><![CDATA[%s]]></url>
      <date year="%s" month="%s" />
      <pages>%s</pages>
    </issue>
''' % (self.number, title, self.url, self.year, self.month, self.pages)

def generateXml(issues):
  title = issues[0].serieTitle
  publisher = issues[0].publisher
  license = issues[0].license
  category = issues[0].category
  status = issues[0].status

  return '''<?xml version="1.0" encoding="UTF-8"?>
<serie>
  <title>%s</title>
  <publisher>%s</publisher>
  <status>%s</status>
  <category>%s</category>
  <license>%s</license>
  <issues>
%s  </issues>
</serie>''' % (title, publisher, status, category, license, "".join(str(i) for i in issues))

baseUrl = sys.argv[1].replace(BASE_URL, '')

serieId = None
match = re.search(r'cod_tit=(.*?)\+?\&esp', baseUrl, re.DOTALL) 
if match:
  serieId = match.group(1)

filePath = DATA_FOLDER + serieId + '.xml'

if os.path.exists(filePath):
  print 'Error: Serie already in collection. Check %s' % filePath
else:
  issue = Issue(baseUrl).parse()
  issues = []
  issues.append(issue)

  for url in issue.urls:
    issues.append(Issue(url).parse())
    
  print '  ... saving'

  fout = open(DATA_FOLDER + serieId + '.xml', "wb")
  fout.write(generateXml(issues))
  fout.close()
